/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package com.yonyou.portcity.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yonyou.portcity.common.exception.RRException;
import com.yonyou.portcity.common.validator.Assert;
import com.yonyou.portcity.entity.UserEntity;
import com.yonyou.portcity.repository.UserRepository;
import com.yonyou.portcity.service.UserService;
import com.yonyou.portcity.utils.WebResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
@Slf4j
public class UserServiceImpl implements UserService {
    private static final Log LOG = LogFactory.getLog(UserServiceImpl.class);
    @Autowired
    private UserRepository userRepository;
	@Override
	public UserEntity queryByuserName(String username) {
		return userRepository.selectOne(new QueryWrapper<UserEntity>().eq("username", username));
	}

    @Override
    public WebResult save(UserEntity userEntity) {
        int id= 0;
        try {
            id = userRepository.insert(userEntity);
            if (id>0){
                return WebResult.success("注册成功");
            }else {
                return WebResult.error("注册失败");
            }
        } catch (Exception e) {
            LOG.error("注册用户错误日志：",e);
            return WebResult.error("注册失败");
        }
    }

    @Override
	public long login(UserEntity form) {
		UserEntity user = queryByuserName(form.getUsername());
		Assert.isNull(user, "用户名或密码错误");

		//密码错误
		if(!user.getPassword().equals(DigestUtils.sha256Hex(form.getPassword()))){
			throw new RRException("用户名或密码错误");
		}

		return user.getUserId();
	}

    @Override
    public WebResult checkUser(String name) {
        UserEntity userEntity= userRepository.selectOne(new QueryWrapper<UserEntity>().eq("username",name));
        if (userEntity!=null){
            return WebResult.error("商户已存在");
        }else {
            return WebResult.success("允许注册");
        }
    }

    @Override
    public WebResult getRegisterUserInfo() {
        return WebResult.success(userRepository.selectCountByCreateTime());
    }
}
